# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QLabel, QVBoxLayout, QFrame, QSizePolicy
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from Ui.chat import Ui_Form
import sys
import socket
from threads import ClientThread


class MessageFrame(QFrame):
    def __init__(self, text: str, is_self: bool = False):
        super().__init__()
        self.show_message(text, is_self)

    def show_message(self, text: str, is_self: bool):
        message = QLabel(self)
        message.setWordWrap(True)
        message.setFixedWidth(450)
        message.setText(text)
        # message.setStyleSheet("background-color: rgb(85, 255, 255);")

        layout = QVBoxLayout(self)
        layout.setContentsMargins(3, 0, 0, 0)
        layout.addWidget(message)

        if is_self:
            layout.setAlignment(Qt.AlignRight | Qt.AlignTop)
            message.setAlignment(Qt.AlignRight)
            message.setContentsMargins(0, 0, 3, 0)

        # self.setStyleSheet("background-color: rgb(255, 170, 0);")
        self.setFixedHeight((message.sizeHint().height() + message.fontMetrics().height()))


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUi()

    def initUi(self):
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.verticalLayout = QVBoxLayout(self.ui.scrollAreaWidgetContents)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setAlignment(Qt.AlignTop)

        # 实例化一个客户端socket
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # 实例化客户端线程
        self.clientThread = ClientThread(self.client_socket)
        self.clientThread.message.connect(self.receive_messages)
        self.clientThread.connect_error.connect(lambda: QMessageBox.warning(self, "错误", "无法连接服务器"))
        self.clientThread.start()

        # 发送按钮绑定
        self.ui.send_btn.clicked.connect(self.send_message)
        # 重置按钮绑定
        self.ui.clear_btn.clicked.connect(lambda: self.ui.plainTextEdit.clear())
        # 实时监控滚动条处于最大值
        self.ui.scrollArea.verticalScrollBar().rangeChanged.connect(self.scrollBar_event)

    def receive_messages(self, message: str):
        self.verticalLayout.addWidget(MessageFrame(
            text=message
        ))

    def send_message(self):
        text = self.ui.plainTextEdit.toPlainText()

        if not text:
            QMessageBox.information(self, "提示", "发送内容不能为空, 请重新输入。")
            return

        self.client_socket.send(text.encode("utf-8"))
        self.verticalLayout.addWidget(MessageFrame(
            text=text,
            is_self=True
        ))
        self.ui.plainTextEdit.clear()

    def scrollBar_event(self, min, max):
        self.ui.scrollArea.verticalScrollBar().setValue(max)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())
